package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private CacheClient cacheClient;

    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @Override
    public Result queryById(Long id) {
        //缓存穿透问题
        Shop shop = queryWithPassThrough(id);  //普通
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES); //使用自己封装的redis工具类
                                                                        //此处this::getById是方法引用 是由普通重写->lambda表达式->方法引用转换过来的
        //利用互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //利用逻辑过期解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id); //普通
        //Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES); //使用自己封装的redis工具类

        //判断是否为null  如果为null  说明是之前设置的缓存穿透措施
        if(shop==null){
            return Result.fail("店铺信息不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 利用互斥锁查询
     * 利用互斥锁解决缓存击穿问题
     */
    public Shop queryWithMutex(Long id){
        //1.从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //存在，返回数据
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3.判断命中的是否是空值
        if (shopJson != null && shopJson.equals("")) {
            //返回错误信息（缓存穿透）
            return null;
        }
        //4.实现缓存重构
        String lockKey=LOCK_SHOP_KEY+id;
        Shop shop;
        try {
            //4.1获取互斥锁
            boolean isLock = tryLock(lockKey);
            //4.2判断获取是否成功
            if(!isLock){
                //失败，休眠重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //成功，查询数据库
            shop = getById(id);
            //5.判断数据是否存在
            if (shop == null) {
                //6.不存在，将空值填入redis，并返回404
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //7.存在，返回数据并写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //8.释放互斥锁
            unLock(lockKey);
        }
        return shop;
    }

    //创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 利用逻辑过期查询
     * 利用逻辑过期解决缓存击穿问题
     */
    public Shop queryWithLogicalExpire(Long id){
        //1.从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //不存在，返回空
            return null;
        }
        //3.存在，把json反序列化成对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Object data = redisData.getData();
        Shop shop = JSONUtil.toBean(data.toString(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4.判断缓存是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回商铺信息
            return shop;
        }
            //过期，缓存重建
        String lockKey=LOCK_SHOP_KEY+id;
        //5.尝试获取互斥锁
        boolean isLock = tryLock(lockKey);
        //6.判断是否获取到互斥锁
        if(isLock){
            //成功，开启独立线程，查询数据库
            CACHE_REBUILD_EXECUTOR.submit(() ->
                    {
                        try {
                            //重建缓存
                            saveShopToRedis(id,20L);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            //释放锁
                            unLock(lockKey);
                        }
                    }
            );
        }
        //失败，返回旧的商铺信息
        return shop;
    }

    /**
     * 解决缓存穿透问题
     */
    private Shop queryWithPassThrough(Long id) {
        //1.从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，返回数据
            return JSONUtil.toBean(shopJson,Shop.class);
        }
        //判断命中的是否是空值
        if (shopJson != null && shopJson.equals("")) {
            //返回错误信息（缓存穿透）
            return null;
        }
        //4.不存在，查询数据库
        Shop shop = getById(id);
        //5.判断数据是否存在
        if (shop == null) {
            //6.不存在，将空值填入redis，并返回404
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //7.存在，返回数据并写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }


    /**
     * 获取锁
     * 利用互斥锁解决缓存击穿问题
     */
    private boolean tryLock(String key){
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "互斥锁", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //Boolean是用于封装基本数据类型的对象类型，有三种取值状态：true  false  null
        //boolean是基本数据类型，不能调用方法，异也不能为null,只能直接存储true或false值
        //所以此处我们需要将Boolean转为boolean基本数据类型，如果直接返回可能会出现空指针异常
        return BooleanUtil.isTrue(ifAbsent);
    }
    /**
     * 释放锁
     * 利用互斥锁解决缓存击穿问题
     */
    private void unLock(String key){
        //直接将锁删掉即可
        stringRedisTemplate.delete(key);
    }

    /**
     * 缓存预热方法
     * 在实际业务中对于热点数据会进行缓存预热
     */
    public void saveShopToRedis(Long id,Long expireSeconds) throws InterruptedException {
        //1.查询店铺数据
        Shop shop = getById(id);
        //模拟缓存重建需要很长时间
        Thread.sleep(200L);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //1.更新数据库
        shopMapper.updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}











